// NoiseFilter.cpp
//
//////////////////////////////////////////////////////////////////////

#include "NoiseFilter.h"
#include <math.h>

#define s_curve(t) ( t * t * (3. - 2. * t) )
#define lerp(t, a, b) ( a + t * (b - a) )
#define setup(i,b0,b1,r0,r1)\
	t = vec[i] + N;\
	b0 = ((int)t) & BM;\
	b1 = (b0+1) & BM;\
	r0 = t - (int)t;\
	r1 = r0 - 1.0;


NoiseFilter::NoiseFilter():start(1){
	
}

NoiseFilter::~NoiseFilter(){

}


float NoiseFilter::bias(float a, float b){
	return pow((float)a, (float)(log(b) / log(0.5)));
}

float NoiseFilter::gain(float a, float b){
	float p = log(1.0 - b) / log(0.5);

	if (a < .001)
		return 0.;
	else if (a > .999)
		return 1.0;
	if (a < 0.5)
		return pow(2 * a, p) / 2;
	else
		return 1.0 - pow((float)(2 * (1.0 - a)), p) / 2;
}


float NoiseFilter::turbulence(float *v, float freq){
	float t, vec[3];

	for (t = 0. ; freq >= 1.0 ; freq /= 2) {
		vec[0] = freq * v[0];
		vec[1] = freq * v[1];
		vec[2] = freq * v[2];
		t += fabs(noise3(vec)) / freq;
	}
	return t;
}


float NoiseFilter::noise1(float arg){
	int bx0, bx1;
	float rx0, rx1, sx, t, u, v, vec[1];

	vec[0] = arg;
	if (start) {
		start = 0;
		init();
	}

	setup(0, bx0,bx1, rx0,rx1);

	sx = s_curve(rx0);

	u = rx0 * g1[ p[ bx0 ] ];
	v = rx1 * g1[ p[ bx1 ] ];

	return lerp(sx, u, v);
}

float NoiseFilter::noise2(float vec[2]){
	int bx0, bx1, by0, by1, b00, b10, b01, b11;
	float rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v;
	register int i, j;

	if (start) {
		start = 0;
		init();
	}

	setup(0, bx0,bx1, rx0,rx1);
	setup(1, by0,by1, ry0,ry1);

	i = p[ bx0 ];
	j = p[ bx1 ];

	b00 = p[ i + by0 ];
	b10 = p[ j + by0 ];
	b01 = p[ i + by1 ];
	b11 = p[ j + by1 ];

	sx = s_curve(rx0);
	sy = s_curve(ry0);

#define at2(rx,ry) ( rx * q[0] + ry * q[1] )

	q = g2[ b00 ] ; u = at2(rx0,ry0);
	q = g2[ b10 ] ; v = at2(rx1,ry0);
	a = lerp(sx, u, v);

	q = g2[ b01 ] ; u = at2(rx0,ry1);
	q = g2[ b11 ] ; v = at2(rx1,ry1);
	b = lerp(sx, u, v);

	return lerp(sy, a, b);
}


float NoiseFilter::noise3(float * vec){
	int bx0, bx1, by0, by1, bz0, bz1, b00, b10, b01, b11;
	float rx0, rx1, ry0, ry1, rz0, rz1, *q, sy, sz, a, b, c, d, t, u, v;
	register int i, j;
	
	if (start) {
		start = 0;
		init();
	}
	
	setup(0, bx0,bx1, rx0,rx1);
	setup(1, by0,by1, ry0,ry1);
	setup(2, bz0,bz1, rz0,rz1);

	i = p[ bx0 ];
	j = p[ bx1 ];

	b00 = p[ i + by0 ];
	b10 = p[ j + by0 ];
	b01 = p[ i + by1 ];
	b11 = p[ j + by1 ];

	t  = s_curve(rx0);
	sy = s_curve(ry0);
	sz = s_curve(rz0);

#define at3(rx,ry,rz) ( rx * q[0] + ry * q[1] + rz * q[2] )

	q = g3[ b00 + bz0 ] ; u = at3(rx0,ry0,rz0);
	q = g3[ b10 + bz0 ] ; v = at3(rx1,ry0,rz0);
	a = lerp(t, u, v);

	q = g3[ b01 + bz0 ] ; u = at3(rx0,ry1,rz0);
	q = g3[ b11 + bz0 ] ; v = at3(rx1,ry1,rz0);
	b = lerp(t, u, v);

	c = lerp(sy, a, b);

	q = g3[ b00 + bz1 ] ; u = at3(rx0,ry0,rz1);
	q = g3[ b10 + bz1 ] ; v = at3(rx1,ry0,rz1);
	a = lerp(t, u, v);

	q = g3[ b01 + bz1 ] ; u = at3(rx0,ry1,rz1);
	q = g3[ b11 + bz1 ] ; v = at3(rx1,ry1,rz1);
	b = lerp(t, u, v);

	d = lerp(sy, a, b);

	return lerp(sz, c, d);
}

void NoiseFilter::normalize2(float v[2]){
	float s;

	s = sqrt(v[0] * v[0] + v[1] * v[1]);
	v[0] = v[0] / s;
	v[1] = v[1] / s;
}

void NoiseFilter::normalize3(float v[3]){
	float s;

	s = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
	v[0] = v[0] / s;
	v[1] = v[1] / s;
	v[2] = v[2] / s;
}

void NoiseFilter::init(void){
	int i, j, k;

	for (i = 0 ; i < B ; i++) {
		p[i] = i;

		g1[i] = (float)((rand() % (B + B)) - B) / B;

		for (j = 0 ; j < 2 ; j++)
			g2[i][j] = (float)((rand() % (B + B)) - B) / B;
		normalize2(g2[i]);

		for (j = 0 ; j < 3 ; j++)
			g3[i][j] = (float)((rand() % (B + B)) - B) / B;
		normalize3(g3[i]);
	}

	while (--i) {
		k = p[i];
		p[i] = p[j = rand() % B];
		p[j] = k;
	}

	for (i = 0 ; i < B + 2 ; i++) {
		p[B + i] = p[i];
		g1[B + i] = g1[i];
		for (j = 0 ; j < 2 ; j++)
			g2[B + i][j] = g2[i][j];
		for (j = 0 ; j < 3 ; j++)
			g3[B + i][j] = g3[i][j];
	}
}


float NoiseFilter::fBm( Vector3D point, float H, float lacunarity, float octaves ){

      float            value, frequency, remainder;
      int               i;
      static int        first = true;
      static float     *exponent_array;

      /* precompute and store spectral weights */
      if ( first ) {
            /* seize required memory for exponent_array */
            exponent_array =
                        (float *)malloc( ((int)octaves+1) * sizeof(float) );
            frequency = 1.0;
            for (i=0; i<=octaves; i++) {
                  /* compute weight for each frequency */
                  exponent_array[i] = pow( frequency, -H );
                  frequency *= lacunarity;
            }
            first = false;
      }

      value = 0.0;            /* initialize vars to proper values */
      frequency = 1.0;

      /* inner loop of spectral construction */
      for (i=0; i<octaves; i++) {
            value += noise3(point ) * exponent_array[i];
            point.x *= lacunarity;
            point.y *= lacunarity;
            point.z *= lacunarity;
      } /* for */

      remainder = octaves - (int)octaves;
      if ( remainder )      /* add in ``octaves''  remainder */
            /* ``i''  and spatial freq. are preset in loop above */
            value += remainder * noise3( point ) * exponent_array[i];

      return( value );

}


float NoiseFilter::
multifractal( Vector3D point, float H, float lacunarity,
              float octaves, float offset ){
      float            value, frequency, remainder;
      int               i;
      static int        first = true;
      static float     *exponent_array;

      /* precompute and store spectral weights */
      if ( first ) {
            /* seize required memory for exponent_array */
            exponent_array =
                        (float *)malloc( ((int)octaves+1) * sizeof(float) );
            frequency = 1.0;
            for (i=0; i<=octaves; i++) {
                  /* compute weight for each frequency */
                  exponent_array[i] = pow( frequency, -H );
                  frequency *= lacunarity;
            }
            first = false;
      }

      value = 1.0;            /* initialize vars to proper values */
      frequency = 1.0;

      /* inner loop of multifractal construction */
      for (i=0; i<octaves; i++) {
            value *= offset * frequency * noise3( point );
            point.x *= lacunarity;
            point.y *= lacunarity;
            point.z *= lacunarity;
      } /* for */

      remainder = octaves - (int)octaves;
      if ( remainder )      /* add in ``octaves''  remainder */
            /* ``i''  and spatial freq. are preset in loop above */
            value += remainder * noise3( point ) * exponent_array[i];

      return value;

}


float NoiseFilter::VLNoise3( Vector3D point, float distortion ){
        Vector3D offset, Vec;
        offset.x = point.x +0.5;        /* misregister domain */
        offset.y = point.y +0.5;
        offset.z = point.z +0.5;
        offset.x *= distortion;         /* scale the randomization */
        offset.y *= distortion;
        offset.z *= distortion;
        return noise3( point );         /* distorted-domain noise */

}



float NoiseFilter::Hetero_Terrain( Vector3D point,
            float H, float lacunarity, float octaves, float offset ){
      float          value, increment, frequency, remainder;
      int             i;
      static int      first = true;
      static float   *exponent_array;

      /* precompute and store spectral weights, for efficiency */
      if ( first ) {
            /* seize required memory for exponent_array */
            exponent_array =
                        (float *)malloc( ((int)octaves+1) * sizeof(float) );
            frequency = 1.0;
            for (i=0; i<=octaves; i++) {
                  /* compute weight for each frequency */
                  exponent_array[i] = pow( frequency, -H );
                  frequency *= lacunarity;
            }
            first = false;
      }

      /* first unscaled octave of function; later octaves are scaled */
      value = offset + noise3( point );
      point.x *= lacunarity;
      point.y *= lacunarity;
      point.z *= lacunarity;

      /* spectral construction inner loop, where the fractal is built */
      for (i=1; i<octaves; i++) {
            /* obtain displaced noise value */
            increment = noise3( point ) + offset;
            /* scale amplitude appropriately for this frequency */
            increment *= exponent_array[i];
            /* scale increment by current `altitude' of function */
            increment *= value;
            /* add increment to ``value''  */
            value += increment;
            /* raise spatial frequency */
            point.x *= lacunarity;
            point.y *= lacunarity;
            point.z *= lacunarity;
      } /* for */

      /* take care of remainder in ``octaves''  */
      remainder = octaves - (int)octaves;
      if ( remainder ) {
            /* ``i''  and spatial freq. are preset in loop above */
            /* note that the main loop code is made shorter here */
            /* you may want to that loop more like this */
            increment = (noise3( point ) + offset) * exponent_array[i];
            value += remainder * increment * value;
      }

      return( value );

}

float NoiseFilter::HybridMultifractal( Vector3D point, float H, float lacunarity,
                    float octaves, float offset ){
      float          frequency, result, signal, weight, remainder;
      int             i;
      static int      first = true;
      static float   *exponent_array;

      /* precompute and store spectral weights */
      if ( first ) {
            /* seize required memory for exponent_array */
            exponent_array =
                        (float *)malloc( ((int)octaves+1) * sizeof(float) );
            frequency = 1.0;
            for (i=0; i<=octaves; i++) {
                  /* compute weight for each frequency */
                  exponent_array[i] = pow( frequency, -H);
                  frequency *= lacunarity;
            }
            first = false;
      }

      /* get first octave of function */
      result = ( noise3( point ) + offset ) * exponent_array[0];
      weight = result;
      /* increase frequency */
      point.x *= lacunarity;
      point.y *= lacunarity;
      point.z *= lacunarity;

      /* spectral construction inner loop, where the fractal is built */
      for (i=1; i<octaves; i++) {
            /* prevent divergence */
            if ( weight > 1.0 )  weight = 1.0;

            /* get next higher frequency */
            signal = ( noise3( point ) + offset ) * exponent_array[i];
            /* add it in, weighted by previous freq's local value */
            result += weight * signal;
            /* update the (monotonically decreasing) weighting value */
            /* (this is why H must specify a high fractal dimension) */
            weight *= signal;

            /* increase frequency */
            point.x *= lacunarity;
            point.y *= lacunarity;
            point.z *= lacunarity;
      } /* for */

      /* take care of remainder in ``octaves''  */
      remainder = octaves - (int)octaves;
      if ( remainder )
            /* ``i''  and spatial freq. are preset in loop above */
            result += remainder * noise3( point ) * exponent_array[i];

      return( result );

}


float NoiseFilter::RidgedMultifractal( Vector3D point, float H, float lacunarity,
                    float octaves, float offset, float gain ){
      float           result, frequency, signal, weight;
      int              i;
      static int       first = true;
      static float    *exponent_array;

      /* precompute and store spectral weights */
      if ( first ) {
            /* seize required memory for exponent_array */
            exponent_array =
                        (float *)malloc( ((int)octaves+1) * sizeof(float) );
            frequency = 1.0;
            for (i=0; i<=octaves; i++) {
                  /* compute weight for each frequency */
                  exponent_array[i] = pow( frequency, -H );
                  frequency *= lacunarity;
            }
            first = false;
      }

      /* get first octave */
      signal = noise3( point );
      /* get absolute value of signal (this creates the ridges) */
      if ( signal < 0.0 ) signal = -signal;
      /* invert and translate (note that "offset" should be ~= 1.0) */
      signal = offset - signal;
      /* square the signal, to increase "sharpness" of ridges */
      signal *= signal;
      /* assign initial values */
      result = signal;
      weight = 1.0;

      for( i=1; i<octaves; i++ ) {
            /* increase the frequency */
            point.x *= lacunarity;
            point.y *= lacunarity;
            point.z *= lacunarity;

            /* weight successive contributions by previous signal */
            weight = signal * gain;
            if ( weight > 1.0 ) weight = 1.0;
            if ( weight < 0.0 ) weight = 0.0;
            signal = noise3( point );
            if ( signal < 0.0 ) signal = -signal;
            signal = offset - signal;
            signal *= signal;
            /* weight the contribution */
            signal *= weight;
            result += signal * exponent_array[i];
      }

      return( result );
}
